const router = require('koa-router')()
//const { getUsers,addUser}=require('../dbop/redis')  //解构赋值

const { getUsers, addUser, deleteUser, getUser } = require('../service/user')
//const todolist=[]


const userlist=[{username:'a@a.com',pwd:'111'}]


router.prefix('/api/user')
router.get('/', async (ctx, next) => {
  // await ctx.render('index', {
  //   title: 'Hello Koa 2!'
  // })
  ctx.body = 'hello koa2'

})

router.post('/testpost', async (ctx, next) => {
  ctx.body = 'koa2 post'
})


router.post('/reg', async (ctx, next) => {

   const data = ctx.request.body

  // userlist.push(data)

  try {
   await addUser(data)
  } catch (error) {
    console.error(error)
  }

  // await addUser(data)
  //  const jstr=JSON.stringify(data)
  //  redisClient.set('todouser',jstr)
  // todolist.push(data)
  ctx.body = "ok!!!"
  //ctx.body =await getUsers()  //'koa2 post'
})
router.post('/login', async (ctx, next) => {

  const data = ctx.request.body
   console.log(data)
  try {
     const r = await getUser(data)


 //const r= userlist.some(item=>item.username==data.username &&item.pwd== data.pwd)
    if (r) {
      ctx.body = { errno: 0, data }

    } else {
      ctx.body ={errno:1,message:'not such user!!'}    //"no such user!!"
    }

  } catch (error) {
    console.error(error)

    ctx.body = "error!!"
  }

  // await addUser(data)
  //  const jstr=JSON.stringify(data)
  //  redisClient.set('todouser',jstr)
  // todolist.push(data)

  //ctx.body =await getUsers()  //'koa2 post'
})

router.post('/deleteuser', async (ctx, next) => {

  const { delid } = ctx.request.body

  ctx.body = await deleteUser(delid)
  // await addUser(data)
  //  const jstr=JSON.stringify(data)
  //  redisClient.set('todouser',jstr)
  // todolist.push(data)

  //"ok!!!"
  //ctx.body =await getUsers()  //'koa2 post'
})



router.post('/clearusers', async (ctx, next) => {

  //const data= ctx.request.body

  // todolist.length=0//'000000'

  //todolist.splice(0,1)
  // ctx.body = todolist.length  //'koa2 post'
})



router.get('/getallusers', async (ctx, next) => {
  ctx.body = await getUsers()

  // ctx.body=[{
  //                   id:2,
  //                   completed:false,
  //                   title:'ksjkafjkjwekjfkjwfjkle'}]
  //testConn()
  //ctx.body=[]
})


// router.get('/api/getallusers', async (ctx, next) => {
//   ctx.body = todolist
// })

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
